const router = require("express").Router();
const { Movie } = require('@/models')
const { data } = require('@/utils/send')
const expressJoi = require('@escook/express-joi')
const { add, put, del } = require('@/joi/movie')

router.get('/', async (req, res) => {
    try {
        const { id } = req.query
        const where = { is_delete: 0 }
        const order = [['id', 'desc']]
        const query = id ? await Movie.findOne({ where: { id } }) : await Movie.findAll({ where, order })
        if (!query) return res.cc('获取电影失败')
        const message = id ? '获取电影列表成功' : '获取电影成功'
        const datas = data({ message, data: query })
        res.send(datas)
        res.locals.data = datas;
    } catch (error) {
        res.cc(error)
    }
})
router.post('/', expressJoi(add), async (req, res) => {
    try {
        const type = await Movie.create(req.body)
        if (!type) return res.cc('添加电影失败')
        const datas = data({ message: '添加电影成功' })
        res.send(datas)
        res.locals.data = datas;
    } catch (error) {
        res.cc(error)
    }
})
router.put('/', expressJoi(put), async (req, res) => {
    try {
        const type = await Movie.update(req.body, { where: { id: req.body.id } })
        if (!type) return res.cc('修改电影失败')
        const datas = data({ message: '修改电影成功' })
        res.send(datas)
        res.locals.data = datas;
    } catch (error) {
        res.cc(error)
    }
})
router.delete('/', expressJoi(del), async (req, res) => {
    try {
        const type = await Movie.update({ is_delete: 1 }, { where: { id: req.query.id } })
        if (!type) return res.cc('删除电影失败')
        const datas = data({ message: '删除电影成功' })
        res.send(datas)
        res.locals.data = datas;
    } catch (error) {
        res.cc(error)
    }
})
module.exports = router;